package com.huluobo.a2207douyindemo.mvvmdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.huluobo.a2207douyindemo.R;
import com.huluobo.a2207douyindemo.databinding.ActivityLoginDemoBinding;
import com.huluobo.a2207douyindemo.mvpdemo.UserBean;

public class LoginMVVMActivity extends AppCompatActivity {

    ActivityLoginDemoBinding binding;
    LoginDemoViewModel vm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_demo);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login_demo);

        //vm不能直接new,需要通过ViewModelProvider来拿对应的class,通过反射的机制啦拿到对应的viewmodel
        vm = new ViewModelProvider(this).get(LoginDemoViewModel.class);

        binding.loginDemoBtn.setOnClickListener(v -> {
            vm.login(binding.loginDemoUsername.getText().toString(), binding.loginDemoPassword.getText().toString());
        });

        vm.success.observe(this, userBean -> {
            Toast.makeText(this, "登录成功:" + userBean.getUsername(), Toast.LENGTH_SHORT).show();
        });

        vm.failed.observe(this, s -> {
            Toast.makeText(this, "登录失败:" + s, Toast.LENGTH_SHORT).show();
        });

    }
}